package com.wenyu.wenyuyuedu.fragment.circlefragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.jingchen.pulltorefresh.PullableListView;
import com.wenyu.wenyuyuedu.R;
import com.wenyu.wenyuyuedu.activity.LoginActivity;
import com.wenyu.wenyuyuedu.activity.MainActivity;
import com.wenyu.wenyuyuedu.activity.SearchActivity;
import com.wenyu.wenyuyuedu.activity.circle.CircleFindDetailActivity;
import com.wenyu.wenyuyuedu.activity.personage.Help_FeedBack_Activity;
import com.wenyu.wenyuyuedu.adapter.circleAdapter.MyCircleFindAdapter;
import com.wenyu.wenyuyuedu.bean.JudgeWhetherJoinBean;
import com.wenyu.wenyuyuedu.bean.circle.MyCircleFind;
import com.wenyu.wenyuyuedu.global.ApiWrapper;
import com.wenyu.wenyuyuedu.server.circle.MyCircleFindServer;
import com.wenyu.wenyuyuedu.server.homepager.JudgeWhetherJoin;
import com.wenyu.wenyuyuedu.utils.AbSharedUtil;
import com.wenyu.wenyuyuedu.utils.MyToast;
import com.wenyu.wenyuyuedu.utils.SharedConstants;
import com.wenyu.wenyuyuedu.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 圈子中发现的fragment
 */
public class Find_Fragment extends Fragment implements View.OnClickListener {


    @InjectView(R.id.rl_personage_search)
    RelativeLayout rlPersonageSearch;
    @InjectView(R.id.my_content_view)
    PullableListView myContentView;
    @InjectView(R.id.my_refresh_view)
    PullToRefreshLayout myRefreshView;
    @InjectView(R.id.iv_defult)
    ImageView ivDefult;
    private View inflate;
    private Intent intent;
    private ListView mListView;
    private String token;
    private int page = 1;
    private boolean isLoading = false;
    private List<MyCircleFind.InfoBean> info;
    private List<MyCircleFind.InfoBean> infoAll = new ArrayList<>();
    private MyCircleFindAdapter adapter;
    private MyCircleFind bodyFind;

    public Find_Fragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        inflate = inflater.inflate(R.layout.fragment_find, container, false);
        StatusBarUtil.setStatusBar(getActivity(), R.color.white);
        ButterKnife.inject(this, inflate);
        initControl();
        initPutoRefresh();
        return inflate;
    }

    @Override
    public void onStart() {
        super.onStart();
        request();
    }

    /*求网络数据*/
    private void request() {
        token = AbSharedUtil.getString(getActivity(), SharedConstants.USER_TOKEN);
        MyCircleFindServer myCircleFindServer = ApiWrapper.getInstance().create(MyCircleFindServer.class);
        Call<MyCircleFind> myCircle = myCircleFindServer.getMyCircle(token, page);
        myCircle.enqueue(new Callback<MyCircleFind>() {
            @Override
            public void onResponse(Call<MyCircleFind> call, Response<MyCircleFind> response) {
                bodyFind = response.body();
                if (bodyFind != null) {
                    int code = bodyFind.getCode();
                    if (code == 1) {
                        info = bodyFind.getInfo();
                        if (info.size() != 0) {
                            if (!isLoading) {
                                infoAll.clear();
                            }
                            infoAll.addAll(info);
                            adapter.AddAll(infoAll, token, bodyFind.getUid());
                            ivDefult.setVisibility(View.GONE);
                        } else {
                            ivDefult.setVisibility(View.VISIBLE);
                        }
                    }else if(code == 3400){
                        ivDefult.setVisibility(View.VISIBLE);
                        infoAll.clear();
                        adapter.AddAll(infoAll, token, bodyFind.getUid());
                    }
                } else {
                    ivDefult.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailure(Call<MyCircleFind> call, Throwable t) {
                ivDefult.setVisibility(View.VISIBLE);
                MyToast.showToast(getActivity(), "网络异常", Toast.LENGTH_SHORT);
            }
        });
    }


    /*
    * 初始化下拉刷新的控件
    * */
    private void initPutoRefresh() {
        mListView = (ListView) myRefreshView.getPullableView();
        myRefreshView.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                new Handler() {
                    public void handleMessage(Message msg) {
                        page = 1;
                        isLoading = false;
                        request();
                        //千万别忘了告诉控件刷新完毕了
                        myRefreshView.refreshFinish(PullToRefreshLayout.SUCCEED);
                    }
                }.sendEmptyMessageDelayed(0, 100);
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                new Handler() {
                    public void handleMessage(Message msg) {
                        page++;
                        isLoading = true;
                        request();
                        //千万别忘了告诉控件刷新完毕了
                        myRefreshView.refreshFinish(PullToRefreshLayout.SUCCEED);
                    }
                }.sendEmptyMessageDelayed(0, 100);
            }
        });
        myContentView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
                /*圈子的id*/
                String circleId = infoAll.get(i).getId();
                JudgeWhetherJoin judgeWhetherJoin = ApiWrapper.getInstance().create(JudgeWhetherJoin.class);
                Call<JudgeWhetherJoinBean> join = judgeWhetherJoin.getJoin(token, circleId);
                join.enqueue(new Callback<JudgeWhetherJoinBean>() {
                    @Override
                    public void onResponse(Call<JudgeWhetherJoinBean> call, Response<JudgeWhetherJoinBean> response) {
                        JudgeWhetherJoinBean body = response.body();
                        if (body != null) {
                            int code = body.getCode();
                            if (code == 1) {
                                //用户已经加入圈子
                                intent.setClass(getActivity(), Help_FeedBack_Activity.class);
                                //创建圈子的名字
                                intent.putExtra("creatorName", infoAll.get(i).getCretorName());
                                //圈子的id
                                intent.putExtra("circleId", infoAll.get(i).getId());
                                //圈子的名字
                                intent.putExtra("circleName", infoAll.get(i).getTitle());
                                //圈子的封面
                                intent.putExtra("circlecover", infoAll.get(i).getCover());
                                /*当前登录用户的uid*/
                                intent.putExtra("login_find_uid", bodyFind.getUid());
                                getActivity().startActivity(intent);
                            } else if (code == 0) {
                                //token错误或失效
                                showLoginDoalog();
                            } else if (code == 1601) {
                                //用户没有加入圈子
                                intent.setClass(getActivity(), CircleFindDetailActivity.class);
                                //圈子的id
                                intent.putExtra("circle_find_id", infoAll.get(i).getId());
                                //圈子的名字
                                intent.putExtra("circle_find_titel", infoAll.get(i).getTitle());
                                //圈子的封面
                                intent.putExtra("circle_find_cover", infoAll.get(i).getCover());
                                //圈子的类名
                                intent.putExtra("circle_find_circletype", infoAll.get(i).getCircleType());
                                //加入圈子的人数
                                intent.putExtra("circle_find_collect_count", infoAll.get(i).getCollect_count());
                                //圈子的简介
                                intent.putExtra("circle_find_content", infoAll.get(i).getContent());
                                //创建圈子的名称
                                intent.putExtra("creatorName", infoAll.get(i).getCretorName());
                                  /*当前登录用户的uid*/
                                intent.putExtra("login_find_uid", bodyFind.getUid());
                                startActivity(intent);
                            } else if (code == 1600) {
                                showLoginDoalog();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<JudgeWhetherJoinBean> call, Throwable t) {
                        MyToast.showToast(getActivity(), "网络异常，请稍后重试！", Toast.LENGTH_SHORT);
                    }
                });
            }
        });
    }

    /*
    * 初始化布局的控件
    * */
    private void initControl() {
        intent = new Intent();
        MainActivity activity = (MainActivity) getActivity();
        adapter = new MyCircleFindAdapter(activity);
        myContentView.setAdapter(adapter);
        rlPersonageSearch.setOnClickListener(this);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            /*
            * 搜索
            * */
            case R.id.rl_personage_search:
                intent.setClass(getActivity(), SearchActivity.class);
                startActivity(intent);
                break;
        }
    }

    android.app.AlertDialog ad;
    private TextView quxiao;
    private TextView queding;

    /*显示登陆的dialog*/
    private void showLoginDoalog() {

        ad = new android.app.AlertDialog.Builder(getActivity()).create();
        ad.show();
        Window window = ad.getWindow();
        window.setContentView(R.layout.dailog_login);
        quxiao = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        queding = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AbSharedUtil.putString(getActivity(), SharedConstants.USER_TOKEN, "");
                Intent intent = new Intent();
                intent.setClass(getActivity(), LoginActivity.class);
                startActivity(intent);
                getActivity().finish();
                ad.dismiss();
            }
        });
    }
}
